package com.keyroy.game.puzzle_rpg.views.listener;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;

public abstract class IntegerTableListener implements TableListener {

	@Override
	public void onSelected(final Table table, final TableEditor tableEditor, final TableItem tableItem,
			final int editIndex) {
		final Spinner spinner = new Spinner(table, SWT.BORDER);
		spinner.setMaximum(999999);
		spinner.setMinimum(-999999);
		try {
			spinner.setSelection(Integer.parseInt(tableItem.getText(editIndex)));
			spinner.addFocusListener(new FocusAdapter() {
				public void focusLost(FocusEvent e) {
					if (onValueChange(spinner.getSelection())) {
						TableItem tableItem = tableEditor.getItem();
						tableItem.setText(editIndex, String.valueOf(spinner.getSelection()));
					}

					spinner.dispose();
				}
			});
			tableEditor.setEditor(spinner, tableItem, editIndex);
			spinner.forceFocus();
			tableItem.setText(editIndex, "");
		} catch (Exception e) {
		}

	}

	public abstract boolean onValueChange(int value);

}
